package com.cn.shuangseqiu.util;

import java.io.InputStream;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class RequestStreamUtil {

	// 服务器地址
	static final String URL = "http://kaijiang.500wan.com/shtml/ssq/";
	// 后缀
	static final String PROCTEIS = ".shtml";

	final static String TAG = "RequestStreamUtil";
	/**
	 * 得到所有的期号
	 */
	public static List<String> getNumNo() {
		List<String> source = new ArrayList<String>();
		String[] maxYear = getYearList();
		int[] maxIndex = getCountList();
		for (int i = 0; i < maxYear.length; i++) {
			for (int j = 1; j <= maxIndex[i]; j++) {
				if(j<10)
					source.add(maxYear[i]+"00"+j);
				else if(j<100)
					source.add(maxYear[i]+"0"+j);
				else
					source.add(maxYear[i]+""+j);
			}
		}
		return source;
	}

	public static Integer getIndexByList(String index,List<String> source){
		for (int i = 0; i < source.size(); i++) {
			if(index.equals(source.get(i))){
				return i;
			}
		}
		return 0;
	}
	/**
	 * 得到所有的红球号码和蓝色号码
	 * 
	 * @param date_num
	 *            期号
	 * @return
	 */
	public static Map<String, Object> getAllNum(String date_num) {
		Map<String, Object> source = null;
		try {
			Document doc;
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			dbf.setNamespaceAware(true);
			DocumentBuilder db = dbf.newDocumentBuilder();
			String sourceStr = "";
			// 服务器路径
			String url = URL + date_num + PROCTEIS;
			sourceStr = connect(url);
			
			//String转换成document
			StringReader str = new StringReader(sourceStr);
			InputSource inputSource = new InputSource(str);
			if (inputSource != null) {
				doc = db.parse(inputSource);
				NodeList nl = doc.getElementsByTagName("table");
				if (null == nl || nl.getLength() == 0)
					return null;
				source = new HashMap<String, Object>();
				nl = nl.item(0).getChildNodes();// tbody

				// 篮球
				NodeList nlBule = nl.item(1).getChildNodes();// 第一个tr集合
				nlBule = nlBule.item(3).getChildNodes();// 第二个td
				source.put("blue", nlBule.item(1).getChildNodes().item(1).getChildNodes().item(13).getChildNodes().item(0).getNodeValue());

				// 红球
				NodeList nlRed = nl.item(3).getChildNodes();// tr集合
				source.put("red", nlRed.item(3).getChildNodes().item(0).getNodeValue().trim());
				return source;
			}
		} catch (Exception e) {
			DebugUtil.debug(TAG, e + "");
		} 
		return source;
	}

	/**
	 * XML对服务器请求服务
	 * 
	 * @param postUrl
	 * @return
	 */
	private static String connect(String postUrl) {
		URL url = null;
		HttpURLConnection urlconn = null;
		InputStream is = null;
		String content = "";
		try {
			url = new URL(postUrl);
			urlconn = (HttpURLConnection) url.openConnection();
			urlconn.setConnectTimeout(30000);
			urlconn.setReadTimeout(30000);
			urlconn.setUseCaches(false); // 设定缓存
			urlconn.setDoOutput(true); // 设定输出URLCONN
			urlconn.setDoInput(true); // 设定输入URLCONN

			is = urlconn.getInputStream();
			int i = -1;
			byte[] b = new byte[1024];
			StringBuffer sb = new StringBuffer();
			while ((i = is.read(b)) != -1) {
				sb.append(new String(b, 0, i));
			}
			content = new String(sb.toString().getBytes("gb2312"),"UTF-8");
			String beginStr = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"1\">";
			content =  content.substring(content.indexOf(beginStr));
			content = content.substring(0, content.indexOf("</table>", 0)+8);
			return content;
		} catch (Exception e) {
			DebugUtil.debug(TAG, e + "");
			return connect(postUrl);
		} finally {
			if (urlconn != null)
				urlconn.disconnect();
		}
	}
	
	/**
	 * 统计一年：星期二，星期四，星期日的个数 从2012年开始
	 * @param year 格式 yyyy
	 * @return
	 */
	public static int getTotalByYear(String year){
		if(year.compareTo("2012")<0)
			return 0;
		String date = year + "-01-01";
		int count = 0;
		SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance(Locale.CHINA);//变换时间
		Calendar calCurrent = Calendar.getInstance(Locale.CHINA);//最大时间
		Date currentDate = cal.getTime();//最大时间
		try {
			calCurrent.setTime(sim.parse(sim.format(currentDate)));//最大时间 yyyy-MM-dd
			cal.setTime(sim.parse(date)); //设置当前时间yyyy-MM-dd
		} catch (Exception e) {
			DebugUtil.debug(TAG, e + ""); 
		}
		/**
		 * 超出时间情形：
		 * 1：同年，变换时间大于当前最大时间
		 * 2：不同年，超出条件年份范围
		 */
	
		if(cal.get(Calendar.YEAR)> calCurrent.get(Calendar.YEAR))
		 //条件年份大于最大年份，直接返回0
		{
			DebugUtil.debug(TAG,"条件年份大于最大年份");
			return 0;
		}
		else if(cal.get(Calendar.YEAR)< calCurrent.get(Calendar.YEAR)) 
		{	//条件年份小于最大年份，设置最大时间为当前年的12-31
			DebugUtil.debug(TAG,"条件年份小于最大年份，设置最大时间为条件年份12月31日");
			calCurrent.set(cal.get(Calendar.YEAR), 12, 31);
		}
			
		//while循环，满足变换时间小于最大时间
		while(cal.getTime().compareTo(calCurrent.getTime()) < 0){
			if(cal.get(Calendar.DAY_OF_WEEK) == 1||//星期日
					cal.get(Calendar.DAY_OF_WEEK) == 3||//星期二
					cal.get(Calendar.DAY_OF_WEEK) == 5)//星期四
				count++;
			cal.add(Calendar.DAY_OF_YEAR, 1);
		}
		
		return count;
	}
	
	/**
	 * 得到年份列表，从2003开始
	 * @return
	 */
	public static String[] getYearList(){
		Calendar cal = Calendar.getInstance(Locale.CHINA);
		int maxYear = cal.get(Calendar.YEAR);
		if(maxYear - 2003 <=0)
			return new String[]{"03","04","05","06","07","08","09","10","11","12"};
		String[] maxYears= new String[maxYear-2003+1];
		for (int i = 2003; i <= maxYear; i++) {
			maxYears[i-2003] = (i+"").substring(2); //后两位
		}
		
		return maxYears;
	}
	
	/**
	 * 得到年份对应的总数
	 * @return
	 */
	public static int[] getCountList(){
		Calendar cal = Calendar.getInstance(Locale.CHINA);
		int maxYear = cal.get(Calendar.YEAR);
		int[] maxs = new int[]{89,122,153,154,153,154,154,153,153,154};
		if(maxYear - 2003 <=0)
			return maxs;
		int[] maxYears= new int[maxYear-2003+1];
		for (int i = 2003; i <= maxYear; i++) {
			if((i-2003) < maxs.length)
				maxYears[i-2003] = maxs[i-2003];
			else
				maxYears[i-2003] = getTotalByYear(i+"");
		}
		return maxYears;
	}
}
